package com.bigShen.util;

import java.io.InputStream;

/**
 * @author : lei.shen
 * @date : 2018/11/29
 */
public class ClassLoaderWrapper {

    ClassLoader defaultClassLoader;
    ClassLoader systemClassLoader;

    public ClassLoaderWrapper() {
        try {
            systemClassLoader = ClassLoader.getSystemClassLoader();
        } catch (RuntimeException e) {
            // ignore
        }
    }

    public InputStream getResourceAsStream(String resource, ClassLoader classLoader) {
        return getResourceAsStream(getClassLoaders(classLoader), resource);
    }

    public InputStream getResourceAsStream(ClassLoader[] classLoaders, String resource) {

        InputStream inputStream = null;
        for (ClassLoader classLoader : classLoaders) {
            if (null != classLoader) {
                inputStream = classLoader.getResourceAsStream(resource);
            }
            if (null != inputStream) {
                return  inputStream;
            }
        }
        return  null;
    }

    public ClassLoader[] getClassLoaders(ClassLoader classLoader) {

        return new ClassLoader[]{
            classLoader,
            defaultClassLoader,
            Thread.currentThread().getContextClassLoader(),
            this.getClass().getClassLoader() ,
            systemClassLoader
        };

    }

}
